package com.room;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.room.observeroom.Score;
import com.room.observeroom.ScoreDao;

import java.util.List;

public class LiveDataActivity extends AppCompatActivity {
    private TextView tv_content;
    private Button btn_insert, btn_delect, btn_update, btn_clear;

    AppDatabase appDatabase;
    ScoreDao scoreDao;
    UserDao userDao;

    LiveData<List<Score>> livedata;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_data);

        tv_content = findViewById(R.id.tv_content);

        btn_insert = findViewById(R.id.btn_insert);
        btn_delect = findViewById(R.id.btn_delect);
        btn_update = findViewById(R.id.btn_update);
        btn_clear = findViewById(R.id.btn_clear);

        appDatabase = AppDatabase.getInstance(this);
        scoreDao = appDatabase.getScoreDao();
        userDao = appDatabase.getUserDao();
        Log.e("TAG", "userdao =" + userDao);

        livedata = scoreDao.getAllScore();

        //观察该方法数据情况
        livedata.observe(this, new Observer<List<Score>>() {
            @Override
            public void onChanged(List<Score> scores) {
                StringBuilder sb = new StringBuilder();
                for (Score s : scores) {
                    sb.append("id:").append(s.getId()).append("科目:").append(s.getTitle())
                            .append("分数:").append(s.getScore()).append("\n");
                }
                tv_content.setText(sb.toString());
            }
        });

        btn_insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Score score1 = new Score(87.5, "语文");
                Score score2 = new Score(78.5, "数学");
                scoreDao.insert(score1, score2);
            }
        });

        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Score s = new Score();
                s.setId(9);
                s.setScore(100);
                scoreDao.update(s);
            }
        });

        btn_delect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Score s = new Score();
                s.setId(10);
                scoreDao.delect(s);
            }
        });

        btn_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scoreDao.clear();
            }
        });

    }
}
